package com.sgb.goods.viewmodel.publish;

import android.text.TextUtils;

import androidx.databinding.ObservableField;
import androidx.lifecycle.MutableLiveData;

import com.sgb.goods.api.GoodsCallBack;
import com.sgb.goods.api.GoodsNet;
import com.sgb.goods.entity.AlbumEntity;
import com.sgb.goods.entity.AliProofEntity;
import com.sgb.goods.entity.ArrEntity;
import com.sgb.goods.entity.AttrChildEntity;
import com.sgb.goods.entity.GetSkuEntity1;
import com.sgb.goods.entity.GoodsPublishEntity;
import com.sgb.goods.entity.GoodsPublishInfoEntity;
import com.sgb.goods.entity.GoodsServicesEntity;
import com.sgb.goods.entity.ProvinceEntity;
import com.sgb.goods.entity.STArrEntity;
import com.sgb.goods.entity.STPublishEntity;
import com.sgb.goods.utils.base.viewmodel.BaseViewModel;
import com.sgb.goods.view.adapter.publish.AdmixtureAdapter;
import com.sgb.goods.view.adapter.publish.ArrAdapter;
import com.sgb.goods.view.adapter.publish.StrengthGradeAdapter;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * 商品发布
 * @author cyj
 */
public class GoodsPublishViewModel extends BaseViewModel {

    public ObservableField<GoodsPublishEntity> goodsPublishEntity = new ObservableField<>(new GoodsPublishEntity());
    public MutableLiveData<GoodsPublishEntity> goodsPublishEntityData = new MutableLiveData<>();
    /** 是否可以填写规格 */
    public MutableLiveData<List<GetSkuEntity1>> getSkuListLD = new MutableLiveData<>();
    /** 出售地区列表 */
    public MutableLiveData<List<ProvinceEntity<List<ProvinceEntity>>>> provinceListLD = new MutableLiveData<>();
    /** 属性列表 */
    public MutableLiveData<List<ArrEntity>> arrListLD = new MutableLiveData<>();
    /** 商品分类列表-UI更新 */
//    public MutableLiveData<List<MenuEntity<MenuEntity<MenuEntity>>>> goodsClassificationLD = new MutableLiveData<>();
    public MutableLiveData<STPublishEntity> sTPublishLD = new MutableLiveData<>();
    public MutableLiveData<Object> isErrorLD = new MutableLiveData<>();
    public MutableLiveData<Object> isSuccessLD = new MutableLiveData<>();
    /** 相册列表 */
    //public MutableLiveData<List<AlbumEntity>> albumListLD = new MutableLiveData<>();
    /** 上传凭证 */
    public MutableLiveData<AliProofEntity> aliProofLD = new MutableLiveData<>();
    /** 获取服务配置 */
    public MutableLiveData<List<GoodsServicesEntity>> goodsServiceListLD = new MutableLiveData<>();
    public List<GoodsServicesEntity> listService;
    public ObservableField<STPublishEntity> sTPublishEntity = new ObservableField<>(new STPublishEntity());
//    private int page = 1;
//    private int size = 20;
    /** 属性 ArrAdapter */
    public ArrAdapter arrAdapter;
    /** 强度等级 adapter */
    public StrengthGradeAdapter strengthGradeAdapter;
    //外加剂 adapter
    public AdmixtureAdapter admixtureAdapter;
    //商品发布要上传的属性列表
    public List<AttrChildEntity> attrChildEntityList;
    //是否重置属性
    public boolean isReset;

    public GoodsPublishViewModel() {
        arrAdapter = new ArrAdapter();
        strengthGradeAdapter = new StrengthGradeAdapter();
        admixtureAdapter = new AdmixtureAdapter();
    }

    /** 获取是否可以填写规格 */
    public void getSku(String cid3) {
        showLoading();
        GoodsNet.getInstance().getGoodsPublishApi().getSku(Long.parseLong(cid3)).enqueue(new GoodsCallBack<BaseEntity<List<GetSkuEntity1>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GetSkuEntity1>> data) {
                getSkuListLD.setValue(data.getData());
            }
        });
    }

    /** 获取出售地区 */
    public void getAreaModel() {
        showLoading();
        GoodsNet.getInstance().getGoodsPublishApi().getCurrentArea().enqueue(new GoodsCallBack<BaseEntity<List<ProvinceEntity<List<ProvinceEntity>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<ProvinceEntity<List<ProvinceEntity>>>> data) {
                provinceListLD.setValue(data.getData());
            }
        });
    }

    /** 获取属性 */
    public void getMaterChoose(String id) {
        String areaCode = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.AREA_CODE, "");
        showLoading();
        GoodsNet.getInstance().getGoodsPublishApi().getMaterChoose(id, areaCode).enqueue(new GoodsCallBack<BaseEntity<List<ArrEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<ArrEntity>> data) {
                arrListLD.setValue(data.getData());
                setArrList(data.getData());
            }
        });
    }

//    /** 获取商品分类 */
//    public void getGoodsCategory() {
//        showLoading();
//        GoodsNet.getInstance().getGoodsPublishApi().goodsCategory().enqueue(new GoodsCallBack<BaseEntity<List<MenuEntity<MenuEntity<MenuEntity>>>>>() {
//            @Override
//            public void onSuccess(BaseEntity<List<MenuEntity<MenuEntity<MenuEntity>>>> data) {
//                goodsClassificationLD.setValue(data.getData());
//            }
//        });
//    }

//    /** 获取相册//2021/1/18 更改为用cid3作为请求参数 */
//    public void getSupplierAlbumByCName(String cid) {
//        showLoading();
//        GoodsNet.getInstance().getGoodsPublishApi().getSupplierAlbumByCName(cid).enqueue(new GoodsCallBack<BaseEntity<List<AlbumEntity>>>() {
//            @Override
//            public void onSuccess(BaseEntity<List<AlbumEntity>> data) {
//                albumListLD.setValue(data.getData());
//            }
//        });
//    }

    /** 获取商品服务配置 */
    public void getServiceCategory(String cid, boolean isST) {
        showLoading();
        GoodsNet.getInstance().getGoodsPublishApi().goodsService(cid).enqueue(new GoodsCallBack<BaseEntity<List<GoodsServicesEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsServicesEntity>> data) {
                // 更新UI
                goodsServiceListLD.setValue(data.getData());
                listService = data.getData();
                List<GoodsPublishInfoEntity> serverInfoDTOS = new ArrayList<>();
                for (int m = 0; m < listService.size(); m++) {
                    for (int n = 0; n < listService.get(m).value.size(); n++) {
                        for (int l = 0; l < listService.get(m).value.get(n).value.size(); l++) {
                            //组装数据到serverInfoDTOS字段下
                            GoodsPublishInfoEntity itemInfo = new GoodsPublishInfoEntity();
                            itemInfo.serviceType = listService.get(m).serviceType;
                            itemInfo.serverName = listService.get(m).value.get(n).value.get(l).serverName;
                            itemInfo.attributeId = listService.get(m).value.get(n).value.get(l).attributeId;
                            itemInfo.attributeName = listService.get(m).value.get(n).value.get(l).attributeName;
                            itemInfo.checked = listService.get(m).value.get(n).value.get(l).checked;
                            itemInfo.customed = listService.get(m).value.get(n).value.get(l).customed;
                            itemInfo.id = listService.get(m).value.get(n).value.get(l).id;
                            itemInfo.sort = listService.get(m).value.get(n).value.get(l).sort;
                            itemInfo.serverName = listService.get(m).value.get(n).value.get(l).serverName;
                            itemInfo.deleted = listService.get(m).value.get(n).value.get(l).deleted;
                            serverInfoDTOS.add(itemInfo);
                        }
                    }
                }
                // 设置发布请求的服务参数  fixme:选择商砼此处为空指针异常
                if(isST) {
                    sTPublishEntity.get().serverInfoDTOS = serverInfoDTOS;
                } else {
                    goodsPublishEntity.get().serverInfoDTOS = serverInfoDTOS;
                }
            }
        });
    }

    /** 获取商品发布 */
    public void goodsPublish() {
        MToast.showLongToast(application.getApplicationContext(),"已注释此功能，暂不使用");
        //移除非必填没有选择属性得选项
//        GoodsPublishEntity entity = goodsPublishEntity.get();
//        if (entity.attrList != null) {
//            ListIterator<AttrChildEntity> iterator = entity.attrList.listIterator();
//            while (iterator.hasNext()) {
//                AttrChildEntity childEntity = iterator.next();
//                if (childEntity.attrValue == null || childEntity.attrValueId == null) {
//                    iterator.remove();
//                }
//            }
//        }
//        showLoading();
//        GoodsNet.getInstance().getGoodsPublishApi().goodsPublish(goodsPublishEntity.get()).enqueue(new GoodsCallBack<BaseEntity<Object>>() {
//            @Override
//            public void onSuccess(BaseEntity<Object> data) {
//                if("53999".equals(data.getErrCode())) {
//                    MToast.showLongToast(application.getApplicationContext(),"销售价不能低于会员价");
//                    return;
//                }
//                isSuccessLD.setValue(true);
//                isError(data.getMsg());
//            }
//
//            @Override
//            public void onFail() {
//                isError("");
//            }
//        });
    }

    /** 获取商品详情 */
    public void getNewGoodsById(String id) {
        showLoading();
        GoodsNet.getInstance().getGoodsPublishApi().getNewGoodsById(id).enqueue(new GoodsCallBack<BaseEntity<GoodsPublishEntity>>() {
            @Override
            public void onSuccess(BaseEntity<GoodsPublishEntity> data) {
                goodsPublishEntity.set(data.getData());
                goodsPublishEntityData.setValue(data.getData());
            }
        });
    }

    /** 获取商砼强度和外加剂 */
    public void concreteAttrs(int type) {
        showLoading();
        GoodsNet.getInstance().getGoodsPublishApi().concreteAttrs().enqueue(new GoodsCallBack<BaseEntity<List<STArrEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<STArrEntity>> data) {
                if (type == 0) {
                    setStrength(data.getData());
                } else {
                    setStrength2(data.getData());
                }
            }
        });
    }

    /** 商砼发布 */
    public void concretePublish() {
        showLoading();
        GoodsNet.getInstance().getGoodsPublishApi().concretePublish(sTPublishEntity.get()).enqueue(new GoodsCallBack<BaseEntity<Object>>() {
            @Override
            public void onSuccess(BaseEntity<Object> data) {
                isSuccessLD.setValue(true);
                isError(data.getMsg());
            }

            @Override
            public void onFail() {
                isError("");
            }
        });
    }

    /** 商砼发布详情 */
    public void concretePublishDetail(String id) {
        showLoading();
        GoodsNet.getInstance().getGoodsPublishApi().concretePublishDetail(id).enqueue(new GoodsCallBack<BaseEntity<STPublishEntity>>() {
            @Override
            public void onSuccess(BaseEntity<STPublishEntity> data) {
                sTPublishEntity.set(data.getData());
                sTPublishLD.setValue(data.getData());
            }
        });
    }

    /** 获取上传凭证 */
    public void getVideoParams() {
        showLoading();
        GoodsNet.getInstance().getGoodsPublishApi().getVideoParams().enqueue(new GoodsCallBack<BaseEntity<AliProofEntity>>() {
            @Override
            public void onSuccess(BaseEntity<AliProofEntity> data) {
                // mDataBinding.nextView.setClickable(false);
                aliProofLD.setValue(data.getData());
            }
        });
    }

    public void isError(String msg) {
        if (!TextUtils.isEmpty(msg) && msg.startsWith("[") && msg.endsWith("]")) {
            //平台已关闭部分服务属性自定义功能，请核对后发布！[1, 583, 589]
            String msgTemp = msg.replace("[", "").replace("]", "");
            if (!TextUtils.isEmpty(msgTemp)) {
                String[] stringArray = msgTemp.split(",");
//            List<String> stringB = new Gson().fromJson(msg, ArrayList.class);
                for (int a = 0; a < stringArray.length; a++) {
                    for (int p = 0; p < listService.size(); p++) {
                        for (int m = 0; m < listService.get(p).value.size(); m++) {
                            if (stringArray[a].trim().equals(String.valueOf(listService.get(p).value.get(m).serverId))) {
                                for (Iterator<GoodsServicesEntity.TypeValue.ItemValue> iterator = listService.get(p).value.get(m).value.iterator(); iterator.hasNext(); ) {
                                    GoodsServicesEntity.TypeValue.ItemValue itemValue = iterator.next();
                                    if (1 == itemValue.customed) {
                                        iterator.remove();
                                    }
                                }
                                listService.get(p).value.get(m).isChange = "1";
                                listService.get(p).value.get(m).serverCustomed = 1;
                            }
                        }
                    }
                }
                List<GoodsPublishInfoEntity> serverInfoDTOS = new ArrayList<>();
                for (int m = 0; m < listService.size(); m++) {
                    for (int n = 0; n < listService.get(m).value.size(); n++) {
                        for (int l = 0; l < listService.get(m).value.get(n).value.size(); l++) {
                            GoodsPublishInfoEntity itemInfo = new GoodsPublishInfoEntity();
                            itemInfo.serviceType = listService.get(m).serviceType;
                            itemInfo.serverName = listService.get(m).value.get(n).value.get(l).serverName;
                            itemInfo.attributeId = listService.get(m).value.get(n).value.get(l).attributeId;
                            itemInfo.attributeName = listService.get(m).value.get(n).value.get(l).attributeName;
                            itemInfo.checked = listService.get(m).value.get(n).value.get(l).checked;
                            itemInfo.customed = listService.get(m).value.get(n).value.get(l).customed;
                            itemInfo.id = listService.get(m).value.get(n).value.get(l).id;
                            itemInfo.sort = listService.get(m).value.get(n).value.get(l).sort;
                            itemInfo.serverId = listService.get(m).value.get(n).serverId;
                            itemInfo.deleted = listService.get(m).value.get(n).value.get(l).deleted;
                            serverInfoDTOS.add(itemInfo);
                        }
                    }
                }
                sTPublishEntity.get().serverInfoDTOS = serverInfoDTOS;
                goodsPublishEntity.get().serverInfoDTOS = serverInfoDTOS;

//                new RoundDialog.Builder(application.getApplicationContext())
//                        .title("温馨提示")
//                        .content("平台已关闭部分服务属性自定义功能，请核对后发布！\n （已为您标记发生变更的服务属性）")
//                        .confirm("知道了")
//                        .singleBtn(true)
//                        .contentGravity(Gravity.CENTER)
//                        .confirmCallback(new RoundDialog.SingleCallback() {
//                            @Override
//                            public void onClick(View v) {
//                                mDataBinding.tvChip.setLabelNameColor(ColorUtils.getColor(R.color.color_EF4033));
//                            }
//                        })
//                        .cancelable(false)
//                        .show();
            }
        }
        isErrorLD.setValue(true);
    }

    public void setStrength(List<STArrEntity> strength) {
        for (int i = 0; i < strength.size(); i++) {
            if ("strength".equals(strength.get(i).name)) {
                strengthGradeAdapter.setNewData(strength.get(i).childList);
            } else if ("admixture".equals(strength.get(i).name)) {
                admixtureAdapter.setNewData(strength.get(i).childList);
            }
        }
    }

    public void setStrength2(List<STArrEntity> strength) {
        for (int i = 0; i < strength.size(); i++) {
            if ("strength".equals(strength.get(i).name)) {
                for (int n = 0; n < sTPublishEntity.get().strengthList.childList.size(); n++) {
                    for (int j = 0; j < strength.get(i).childList.size(); j++) {
                        if (sTPublishEntity.get().strengthList.childList.get(n).name.equals(strength.get(i).childList.get(j).name)) {
                            strength.get(i).childList.get(j).price = sTPublishEntity.get().strengthList.childList.get(n).price;
                        }
                    }
                }
                strengthGradeAdapter.setNewData(strength.get(i).childList);
            } else if ("admixture".equals(strength.get(i).name)) {
                for (int n = 0; n < sTPublishEntity.get().admixtureList.childList.size(); n++) {
                    for (int j = 0; j < strength.get(i).childList.size(); j++) {
                        if (sTPublishEntity.get().admixtureList.childList.get(n).name.equals(strength.get(i).childList.get(j).name)
                                && sTPublishEntity.get().admixtureList.childList.get(n).spec.equals(strength.get(i).childList.get(j).spec)) {
                            strength.get(i).childList.get(j).price = sTPublishEntity.get().admixtureList.childList.get(n).price;
                        }
                    }
                }
                admixtureAdapter.setNewData(strength.get(i).childList);
            }
        }
    }

    //动态设置属性列表
    public void setArrList(List<ArrEntity> data) {
        if (data != null && data.size() != 0) {
            //新增时无ID，编辑时有ID
            if (goodsPublishEntity.get().id == null) {
                newData(data);
                arrAdapter.setNewData(data);
            } else {
                if (isReset) {
                    newData(data);
                } else {
                    for (int i = 0; i < goodsPublishEntity.get().attrList.size(); i++) { //编辑时走这里
                        for (int j = 0; j < data.size(); j++) {
                            if (data.get(j).name.equals(goodsPublishEntity.get().attrList.get(i).attrKey)) {
                                data.get(j).content = goodsPublishEntity.get().attrList.get(i).attrValue;
                            }
                        }
                    }
                    //新建一个列表整合选中和未选中的属性
                    List<AttrChildEntity> attrTempList = new ArrayList<>();
                    for (int m = 0; m < data.size(); m++) {
                        AttrChildEntity attrChildEntity = new AttrChildEntity();
                        attrChildEntity.attrKey = data.get(m).name;
                        attrChildEntity.attrKeyId = data.get(m).id;
                        attrChildEntity.isfill = data.get(m).isfill;
                        attrTempList.add(attrChildEntity);
                    }

                    for (int n = 0; n < goodsPublishEntity.get().attrList.size(); n++) {
                        for (int a = 0; a < attrTempList.size(); a++) {
                            if (attrTempList.get(a).attrKey.equals(goodsPublishEntity.get().attrList.get(n).attrKey)) {
                                attrTempList.get(a).attrValue = goodsPublishEntity.get().attrList.get(n).attrValue;
                                attrTempList.get(a).attrValueId = goodsPublishEntity.get().attrList.get(n).attrValueId;
                            }
                        }
                    }
                    attrChildEntityList = attrTempList;
                }
                arrAdapter.setNewData(data);
                isReset = false;
            }
        }
    }

    private void newData(List<ArrEntity> data) {
        arrAdapter.isReset(true);
        if (attrChildEntityList == null) {
            attrChildEntityList = new ArrayList<>();
        }
        attrChildEntityList.clear();
        if (data != null) {
            for (int i = 0; i < data.size(); i++) {
                AttrChildEntity attrChildEntity = new AttrChildEntity();
                attrChildEntity.attrKey = data.get(i).name;
                attrChildEntity.attrKeyId = data.get(i).id;
                attrChildEntity.isfill = data.get(i).isfill;
                attrChildEntityList.add(attrChildEntity);
            }
            goodsPublishEntity.get().attrList = attrChildEntityList;
        }
    }
}
